<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/10/2
 * Time: 11:02
 */
class UploadFile
{
    private static $ci = null;
    private $default_config = [];
    private $default_config_path = __DIR__.'/upload_config.json';

    public function __construct(Array $config_jsons=[])
    {
      if(empty(self::$ci))
      {
          self::$ci = &get_instance();
      }
      self::$ci->load->library("upload");


      foreach ($config_jsons as $config_json)
      {
          $this->loadConfig(__DIR__.'/'.$config_json);
      }
      $this->loadConfig($this->default_config_path);
    }

    //上传文件
    public function uploadFile($form_field_name)
    {
        self::$ci->upload->initialize($this->default_config);
        $res = self::$ci->upload->do_upload($form_field_name);
        if($res)
        {
            return self::$ci->upload->data();
        }
        else
        {
            return self::$ci->upload->display_errors('<p>', '</p>');
        }
    }

    //加载配置文件
    private function loadConfig($path)
    {
        $config_json_str = @file_get_contents($path);
        $new_config = json_decode($config_json_str,true);

        $this->default_config = array_merge($this->default_config,$new_config);
    }
}